package com.easy.carl.algorithm.linkNode;

import com.easy.leetcode.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 */
public class RemoveNthFromEnd19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //临时节点
        ListNode dummyNode = new ListNode(-1, head);
        //快指针
        ListNode quickNode = head;
        //慢指针
        ListNode slowNode = null;
        //两个指针相隔的距离
        int i = 1;
        while (quickNode != null) {
            //达到指定的距离
            if (i == n) {
                //慢指针开始
                slowNode = dummyNode;
            } else if (i > n) {
                slowNode = slowNode.next;
            }
            i++;
            quickNode = quickNode.next;
        }
        if (slowNode != null) {
            slowNode.next = slowNode.next.next;
        }
        return dummyNode.next;
    }

    public static void main(String[] args) {
        ListNode listNode = ListNodeHelp.helpBuild(new int[]{1,2,3,4,5});
        RemoveNthFromEnd19 removeNthFromEnd19 = new RemoveNthFromEnd19();
        listNode = removeNthFromEnd19.removeNthFromEnd(listNode, 2);
        ListNodeHelp.helpPrint(listNode);
    }
}
